import 'package:flutter/material.dart';
import 'package:ly_music/utils/config.dart';
import 'dart:async';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../models/song.dart';
import '../services/music_player_service.dart';
import '../utils/lyric_parser.dart';
import '../models/playlist.dart';
import '../services/playlist_management_service.dart';
import '../services/favorites_service.dart';
import '../services/history_service.dart';
import '../utils/util.dart';

class PlayerSheetWidget extends StatefulWidget {
  const PlayerSheetWidget({super.key});

  @override
  State<PlayerSheetWidget> createState() => _PlayerSheetWidgetState();
}

class _PlayerSheetWidgetState extends State<PlayerSheetWidget> {
  final ScrollController _scrollController = ScrollController();
  int _lastLyricIndex = -1;
  String? _playModeTip;
  Timer? _tipTimer;
  bool _isFavorite = false;

  @override
  void dispose() {
    _scrollController.dispose();
    _tipTimer?.cancel();
    super.dispose();
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerService>(
      builder: (context, playerService, child) {
        final currentSong = playerService.currentSong;
        if (currentSong == null) {
          return const SizedBox.shrink();
        }

        WidgetsBinding.instance.addPostFrameCallback((_) async {
          final song = playerService.currentSong;
          if (song != null) {
            final fav = await FavoritesService.isFavorite(song);
            if (mounted && fav != _isFavorite) {
              setState(() { _isFavorite = fav; });
            }
          }
        });

        return GestureDetector(
          onTap: () {
            // 点击空白区域时关闭播放器
            Navigator.pop(context);
          },
          child: SizedBox.expand(
            child: Column(
              children: [
              // 上方内容区域（带背景图）
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      // 阻止事件冒泡到外层，防止意外关闭
                    },
                    child: Stack(
                  children: [
                    // 使用渐变背景替代专辑图背景
                    Positioned.fill(
                      child: Container(
                        decoration: const BoxDecoration(
                          // 黑胶风格深色渐变
                          gradient: LinearGradient(
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                            colors: [
                              Color(0xFF0E0E0E), // 深黑灰
                              Color.fromARGB(255, 129, 124, 124), // 中段黑
                              Color.fromARGB(255, 27, 26, 26), // 低端黑
                            ],
                          ),
                        ),
                      ),
                    ),
                    // 半透明遮罩，提升歌词可读性
                    Positioned.fill(
                      child: Container(
                        color: Colors.black.withOpacity(0.4),
                      ),
                    ),
                    // 内容区域
                    Column(
                      children: [
                        // 拖拽指示器
                        Container(
                          width: 40,
                          height: 4,
                          margin: const EdgeInsets.symmetric(vertical: 12),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.6),
                            borderRadius: BorderRadius.circular(2),
                          ),
                        ),
                        // 顶部操作栏
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              IconButton(
                                onPressed: () => Navigator.pop(context),
                                icon: const Icon(Icons.keyboard_arrow_down, color: Colors.white),
                              ),
                              Text(
                                '正在播放',
                                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                              const SizedBox(width: 48), // 占位，保持布局对称
                            ],
                          ),
                        ),
                        const SizedBox(height: 20),
                        // 歌词和专辑图内容区域
                        Expanded(
                          child: _buildContentArea(currentSong),
                        ),
                      ],
                    ),
                  ],
                    ),
                  ),
                ),
              // 下方控制区域（独立背景）
              GestureDetector(
                onTap: () {
                  // 阻止事件冒泡，防止意外关闭播放器
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surface,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.1),
                        blurRadius: 8,
                        offset: const Offset(0, -2),
                      ),
                    ],
                  ),
                  child: _buildControlsSection(playerService),
                ),
              ),
              ],
            ),
          ),
        );
      },
    );
  }



  Widget _buildContentArea(Song song) {
    return Column(
      children: [
        // 歌曲信息区域
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 32),
          child: Column(
            children: [
              Text(
                song.name,
                style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      offset: const Offset(0, 1),
                      blurRadius: 3,
                      color: Colors.black.withOpacity(0.8),
                    ),
                  ],
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
              Text(
                song.artistsString,
                style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  color: Colors.white.withOpacity(0.9),
                  shadows: [
                    Shadow(
                      offset: const Offset(0, 1),
                      blurRadius: 3,
                      color: Colors.black.withOpacity(0.8),
                    ),
                  ],
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),
        // 响应式布局：根据屏幕宽度决定是否显示专辑图
        Expanded(
          child: LayoutBuilder(
            builder: (context, constraints) {
              final isWideScreen = CommonUtils.isWideScreen(context); 
              if (isWideScreen) {
                // 大屏幕：左侧专辑图，右侧歌词
                return Row(
                  children: [
                    // 左侧：专辑图
                    Expanded(
                      flex: 2,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: AspectRatio(
                          aspectRatio: 1,
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(16),
                            child: song.albumImageUrl != null
                                ? CachedNetworkImage(
                                    imageUrl: song.albumImageUrl!,
                                    fit: BoxFit.cover,
                                    placeholder: (context, url) => Container(
                                      color: Colors.white.withOpacity(0.1),
                                      child: const Icon(Icons.music_note, size: 80, color: Colors.white),
                                    ),
                                    errorWidget: (context, url, error) => Container(
                                      color: Colors.white.withOpacity(0.1),
                                      child: const Icon(Icons.music_note, size: 80, color: Colors.white),
                                    ),
                                  )
                                : Container(
                                    color: Colors.white.withOpacity(0.1),
                                    child: const Icon(Icons.music_note, size: 80, color: Colors.white),
                                  ),
                          ),
                        ),
                      ),
                    ),
                    // 右侧：歌词
                    Expanded(
                      flex: 3,
                      child: Container(
                        padding: const EdgeInsets.only(right: 16),
                        child: _buildLyricsView(song),
                      ),
                    ),
                  ],
                );
              } else {
                // 小屏幕：只显示歌词，隐藏专辑图
                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: _buildLyricsView(song),
                );
              }
            },
          ),
        ),
      ],
    );
  }

  Widget _buildLyricsView(Song song) {
    return Consumer<MusicPlayerService>(
      builder: (context, playerService, child) {
        final lyrics = LyricParser.parseLyric(song.lyric);
        final currentIndex = LyricParser.getCurrentLyricIndex(lyrics, playerService.position);

        // 调试信息（可以在开发时启用）
        // print('当前播放时间: ${playerService.position.inSeconds}s, 歌词索引: $currentIndex');
        // if (currentIndex >= 0 && currentIndex < lyrics.length) {
        //   print('当前歌词: ${lyrics[currentIndex].text}');
        // }

        // 自动滚动到当前歌词行
        if (currentIndex != _lastLyricIndex && currentIndex >= 0 && lyrics.isNotEmpty) {
          _lastLyricIndex = currentIndex;
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (_scrollController.hasClients) {
              final itemHeight = 60.0; // 调整每行高度
              final screenHeight = MediaQuery.of(context).size.height * 0.4;
              final centerOffset = screenHeight / 2;
              final targetOffset = (currentIndex * itemHeight) - centerOffset;
              
              _scrollController.animateTo(
                targetOffset.clamp(0.0, _scrollController.position.maxScrollExtent),
                duration: const Duration(milliseconds: 500),
                curve: Curves.easeInOut,
              );
            }
          });
        }

        return Container(
          height: double.infinity,
          child: lyrics.isNotEmpty
              ? _buildLyricsList(lyrics, currentIndex, context)
              : Center(
                  child: Text(
                    '暂无歌词',
                    style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                      color: Colors.white.withOpacity(0.7),
                      shadows: [
                        Shadow(
                          offset: const Offset(0, 1),
                          blurRadius: 3,
                          color: Colors.black.withOpacity(0.8),
                        ),
                      ],
                    ),
                  ),
                ),
        );
      },
    );
  }

  Widget _buildLyricsList(List<LyricLine> lyrics, int currentIndex, BuildContext context) {
    return ListView.builder(
      controller: _scrollController,
      itemCount: lyrics.length,
      itemBuilder: (context, index) {
        final isCurrentLine = index == currentIndex;
        final lyricLine = lyrics[index];

        return Container(
          height: 60.0, // 固定行高，与滚动计算保持一致
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
          child: Center(
            child: Text(
              lyricLine.text,
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                color: isCurrentLine
                    ? Colors.white
                    : Colors.white.withOpacity(0.8),
                fontWeight: isCurrentLine ? FontWeight.bold : FontWeight.normal,
                fontSize: isCurrentLine ? 20 : 16,
                height: 1.2,
                shadows: [
                  Shadow(
                    offset: const Offset(0, 1),
                    blurRadius: isCurrentLine ? 4 : 3,
                    color: Colors.black.withOpacity(0.8),
                  ),
                ],
              ),
              textAlign: TextAlign.center,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        );
      },
    );
  }

  Widget _buildControlsSection(MusicPlayerService playerService) {
    final isWide = CommonUtils.isWideScreen(context);
    final hPadding = isWide ? 36.0 : 4.0;
    final gap = isWide ? 20.0 : 2.0;
    final smallGap = isWide ? 18.0 : 4.0;
    return Padding(
      padding: EdgeInsets.fromLTRB(
        hPadding,
        8,
        hPadding,
        MediaQuery.of(context).padding.bottom + 8,
      ),
      child: Column(
        children: [
          // 播放模式提示（短暂显示）
          AnimatedSwitcher(
            duration: const Duration(milliseconds: 250),
            child: (_playModeTip != null)
                ? Padding(
                    padding: const EdgeInsets.only(bottom: 4),
                    child: Text(
                      '播放模式：$_playModeTip',
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                    ),
                  )
                : const SizedBox.shrink(),
          ),
          // 时间 + 进度条合并为同一行，降低整体高度
          Row(
            children: [
              Text(
                _formatDuration(playerService.position),
                style: Theme.of(context).textTheme.bodySmall,
              ),
              SizedBox(width: smallGap),
              Expanded(
                child: SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5),
                    trackHeight: 2,
                  ),
                  child: Slider(
                    value: playerService.progress.clamp(0.0, 1.0),
                    onChanged: (value) {
                      final position = Duration(
                        milliseconds: (value * playerService.duration.inMilliseconds).round(),
                      );
                      playerService.seekTo(position);
                    },
                    onChangeEnd: (value) {
                      // 拖拽结束时立即执行seek，确保最终位置准确
                      final position = Duration(
                        milliseconds: (value * playerService.duration.inMilliseconds).round(),
                      );
                      playerService.seekToImmediate(position);
                    },
                  ),
                ),
              ),
              SizedBox(width: smallGap),
              Text(
                _formatDuration(playerService.duration),
                style: Theme.of(context).textTheme.bodySmall,
              ),
            ],
          ),

          SizedBox(height: isWide ? 12 : 8),

          // 播放控制按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 播放模式
              IconButton(
                onPressed: () {
                  final modes = PlayMode.values;
                  final currentIndex = modes.indexOf(playerService.playMode);
                  final nextMode = modes[(currentIndex + 1) % modes.length];
                  playerService.setPlayMode(nextMode);
                  // 中文提示当前播放模式（内嵌提示）
                  final label = _getPlayModeLabel(nextMode);
                  _showPlayModeTip(label);
                },
                icon: Icon(_getPlayModeIcon(playerService.playMode)),
                tooltip: '切换播放模式',
                iconSize: 24,
              ),
              SizedBox(width: gap),
              // 喜欢
              IconButton(
                onPressed: () async {
                  final song = playerService.currentSong;
                  if (song == null) return;
                  if (_isFavorite) {
                    await FavoritesService.removeFromFavorites(song);
                  } else {
                    await FavoritesService.addToFavorites(song);
                    await HistoryService.addToHistory(song);
                  }
                  if (mounted) {
                    setState(() { _isFavorite = !_isFavorite; });
                  }
                },
                icon: Icon(
                  _isFavorite ? Icons.favorite : Icons.favorite_border,
                  color: _isFavorite ? Colors.red : null,
                ),
                tooltip: '喜欢',
                iconSize: 24,
              ),
              SizedBox(width: gap),
              // 上一首
              IconButton(
                onPressed: playerService.hasPrevious ? playerService.previous : null,
                icon: const Icon(Icons.skip_previous),
                iconSize: 28,
                tooltip: '上一首',
              ),
              SizedBox(width: gap),
              // 播放/暂停
              Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.primary,
                  shape: BoxShape.circle,
                ),
                child: IconButton(
                  onPressed: playerService.togglePlayPause,
                  icon: Icon(
                    playerService.isPlaying
                        ? Icons.pause
                        : playerService.isLoading
                            ? Icons.hourglass_empty
                            : Icons.play_arrow,
                    color: Theme.of(context).colorScheme.onPrimary,
                  ),
                  iconSize: 32,
                ),
              ),
              SizedBox(width: gap),
              // 下一首
              IconButton(
                onPressed: playerService.hasNext ? playerService.next : null,
                icon: const Icon(Icons.skip_next),
                iconSize: 28,
                tooltip: '下一首',
              ),
              SizedBox(width: gap),
              // 添加到歌单
              IconButton(
                onPressed: _addToCustomPlaylist,
                icon: const Icon(Icons.playlist_add),
                tooltip: '添加到歌单',
                iconSize: 24,
              ),
              SizedBox(width: gap),
              // 音量
              IconButton(
                onPressed: () => _showVolumeControl(context, playerService),
                icon: Icon(_getVolumeIcon(playerService.volume)),
                iconSize: 24,
                tooltip: '调整音量',
              ),
            ],
          ),
        ],
      ),
    );
  }

  IconData _getPlayModeIcon(PlayMode mode) {
    switch (mode) {
      case PlayMode.sequence:
        return Icons.playlist_play;
      case PlayMode.loop:
        return Icons.repeat;
      case PlayMode.single:
        return Icons.repeat_one;
      case PlayMode.shuffle:
        return Icons.shuffle;
    }
  }

  String _getPlayModeLabel(PlayMode mode) {
    switch (mode) {
      case PlayMode.sequence:
        return '顺序播放';
      case PlayMode.loop:
        return '列表循环';
      case PlayMode.single:
        return '单曲循环';
      case PlayMode.shuffle:
        return '随机播放';
    }
  }

  void _showPlayModeTip(String label) {
    setState(() {
      _playModeTip = label;
    });
    _tipTimer?.cancel();
    _tipTimer = Timer(const Duration(milliseconds: 1200), () {
      if (!mounted) return;
      setState(() {
        _playModeTip = null;
      });
    });
  }

  Future<void> _addToCustomPlaylist() async {
    final playerService = Provider.of<MusicPlayerService>(context, listen: false);
    final Song? currentSong = playerService.currentSong;
    if (currentSong == null) return;

    final playlists = await PlaylistManagementService.getPlaylists();

    Playlist? target;
    if (playlists.isEmpty) {
      final name = await _promptPlaylistName();
      if (name == null || name.trim().isEmpty) return;
      target = await PlaylistManagementService.createPlaylist(name.trim());
    } else {
      target = await _choosePlaylistDialog(playlists);
      if (target == null) return;
    }

    await PlaylistManagementService.addSongTo(target.id, currentSong);
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('已添加到“${target.name}”')),
      );
    }
  }

  Future<String?> _promptPlaylistName() async {
    final controller = TextEditingController();
    return showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('新建歌单'),
          content: TextField(
            controller: controller,
            autofocus: true,
            decoration: const InputDecoration(hintText: '请输入歌单名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, controller.text), child: const Text('确定')),
          ],
        );
      },
    );
  }

  Future<Playlist?> _choosePlaylistDialog(List<Playlist> playlists) async {
    return showDialog<Playlist>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('选择歌单'),
          content: SizedBox(
            width: 360,
            child: ListView.separated(
              shrinkWrap: true,
              itemCount: playlists.length,
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (context, index) {
                final p = playlists[index];
                return ListTile(
                  title: Text(p.name),
                  subtitle: Text('${p.songs.length} 首'),
                  onTap: () => Navigator.pop(context, p),
                );
              },
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
            TextButton(
              onPressed: () async {
                final name = await _promptPlaylistName();
                if (name != null && name.trim().isNotEmpty) {
                  final created = await PlaylistManagementService.createPlaylist(name.trim());
                  if (context.mounted) Navigator.pop(context, created);
                }
              },
              child: const Text('新建歌单'),
            ),
          ],
        );
      },
    );
  }

  IconData _getVolumeIcon(double volume) {
    if (volume == 0) {
      return Icons.volume_off;
    } else if (volume < 0.5) {
      return Icons.volume_down;
    } else {
      return Icons.volume_up;
    }
  }

  void _showVolumeControl(BuildContext context, MusicPlayerService playerService) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: const Text('音量控制'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Icon(_getVolumeIcon(playerService.volume)),
                      const SizedBox(width: 16),
                      Expanded(
                        child: Slider(
                          value: playerService.volume,
                          min: 0.0,
                          max: 1.0,
                          divisions: 20,
                          label: '${(playerService.volume * 100).round()}%',
                          onChanged: (value) {
                            setState(() {
                              playerService.setVolume(value);
                            });
                          },
                        ),
                      ),
                      const SizedBox(width: 16),
                      Text('${(playerService.volume * 100).round()}%'),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      TextButton(
                        onPressed: () => playerService.setVolume(0.0),
                        child: const Text('静音'),
                      ),
                      TextButton(
                        onPressed: () => playerService.setVolume(0.5),
                        child: const Text('50%'),
                      ),
                      TextButton(
                        onPressed: () => playerService.setVolume(1.0),
                        child: const Text('100%'),
                      ),
                    ],
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('关闭'),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
